import {
  Cesium3DTileset,
  HeadingPitchRange,
  Cesium3DTileStyle,
  Cesium3DTileFeature,
  Color
} from 'cesium'
import { mouseMove } from '../../utils/handler'

const add3dTileset = async (viewer, opts = {}) => {
  try {
    const tileset = await Cesium3DTileset.fromUrl(opts.url)
    viewer.scene.primitives.add(tileset)
    viewer.zoomTo(
      tileset,
      new HeadingPitchRange(0.0, -0.5, tileset.boundingSphere.radius * 2.0)
    )
    console.log('tileset', tileset)
    // 注册cesium鼠标移动事件
    mouseMove(viewer, movement => {
      const feature = viewer.scene.pick(movement.endPosition)
      if (feature instanceof Cesium3DTileFeature) {
        const propertyIds = feature.getPropertyIds()
        const length = propertyIds.length
        for (let i = 0; i < length; ++i) {
          const propertyId = propertyIds[i]
          console.log(`{propertyId}: ${feature.getProperty(propertyId)}`)
        }
      }
    })
    const style = new Cesium3DTileStyle()
    style.color = {
      evaluateColor: (feature, result) => {
        console.log('feature', feature)
        return Color.clone(Color.WHITE, result)
      }
    }
    tileset.style = style
    // tileset.style = new Cesium3DTileStyle({
    //   color: {
    //     conditions: [
    //       ['${Height} >= 100', 'color("purple", 0.5)'],
    //       ['${Height} >= 50', 'color("red")'],
    //       ['true', 'color("blue")']
    //     ]
    //   },
    //   show: '${Height} > 0',
    //   meta: {
    //     description: '"Building id ${id} has height ${Height}."'
    //   }
    // })
    // const defaultStyle = new Cesium3DTileStyle({
    //   color: "color('gray', 0.5)", // 让建筑变透明
    //   show: true
    // })

    // tileset.style = defaultStyle
  } catch (error) {
    console.log(`Error loading  tileset: ${error}`)
  }
}

export { add3dTileset }
